package com.jiang.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiang.dto.Result;
import com.jiang.entity.ShopType;
import com.jiang.mapper.ShopTypeMapper;
import com.jiang.service.IShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.jiang.utils.RedisConstants.CACHE_TYPE_KEY;
import static com.jiang.utils.RedisConstants.CACHE_TYPE_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiang
 * @since 2024-3-20
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryByTypeList() {
        // 1、从redis查询店铺类型
        List<String> typeList = stringRedisTemplate.opsForList().range(CACHE_TYPE_KEY, 0, -1);
        // 2、判断是否存在
        if (typeList != null && !typeList.isEmpty()) {
            List<ShopType> temp = new ArrayList<>();
            for (String s : typeList) {
                temp.add(JSONUtil.toBean(s, ShopType.class));
            }
            return Result.ok(temp);
        }
        // 4、不存在， 查询数据库
        List<ShopType> typeListSql = this.query().orderByAsc("sort").list();
        System.out.println("typeListSql = " + typeListSql);
        // 5、写入redis
        List<String> temp = new ArrayList<>();
        for (ShopType s : typeListSql) {
            temp.add(JSONUtil.toJsonStr(s));
        }
        stringRedisTemplate.opsForList().leftPushAll(CACHE_TYPE_KEY, temp);
        stringRedisTemplate.expire(CACHE_TYPE_KEY, CACHE_TYPE_TTL, TimeUnit.MINUTES);
        // 6、返回
        return Result.ok(typeListSql);
    }
}
